package com.gitee.hljdrl.dialog.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;

import com.gitee.hljdrl.dialog.R;
import com.gitee.hljdrl.dialog.basis.OnUIScrollListener;

/**
 * 1.适配最大高度
 * 2.增加滑动开始事件和滑动结束事件
 */
public class UIScrollView extends android.widget.ScrollView {

    private int mMaxHeight;

    /**
     * Runnable延迟执行的时间
     */
    private final long delayMillis = 100;

    /**
     * 上次滑动的时间
     */
    private long lastScrollUpdate = -1;
    private OnUIScrollListener onUIScrollListener;
    private final Runnable scrollerTask = new Runnable() {
        @Override
        public void run() {
            long currentTime = System.currentTimeMillis();
            if ((currentTime - lastScrollUpdate) > 100) {
                lastScrollUpdate = -1;
                onScrollEnd();
            } else {
                postDelayed(this, delayMillis);
            }
        }
    };

    public UIScrollView(Context context) {
        this(context, null);
    }

    public UIScrollView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public UIScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.UIDialog);
        mMaxHeight = typedArray.getDimensionPixelSize(R.styleable.UIDialog_maxUIHeight, 0);
        typedArray.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mMaxHeight != 0) {
            super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(mMaxHeight, MeasureSpec.AT_MOST));
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    public void setMaxHeight(int mMaxHeight) {
        this.mMaxHeight = mMaxHeight;
        requestLayout();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);

        if (lastScrollUpdate == -1) {
            onScrollStart();
            postDelayed(scrollerTask, delayMillis);
        }
        // 更新ScrollView的滑动时间
        lastScrollUpdate = System.currentTimeMillis();
    }

    /**
     * 滑动开始
     */
    private void onScrollStart() {
        if (onUIScrollListener != null) {
            onUIScrollListener.onScrollStart();
        }
    }

    /**
     * 滑动结束
     */
    private void onScrollEnd() {
        if (onUIScrollListener != null) {
            onUIScrollListener.onScrollEnd();
        }
    }

    public void setOnUIScrollListener(OnUIScrollListener mOnFFScrollListener) {
        this.onUIScrollListener = mOnFFScrollListener;
    }
}
